<template>
  <div>
    <div>支持选择其它项目已有的连接或者新建数据库连接<el-button class="new-link-btn" type="text" @click="addLink"><i class="new-link-icon el-icon-folder-add"></i>新建连接</el-button></div>
    <div class="link-list" v-show="linkList.length">
      <div
        v-for="(item, index) in linkList"
        :key="index"
        class="link-item"
        :class="{ 'active': item.id === curLink.id}"
        @click="chooseLink(item)">
        <div class="link-item-left">
          <div class="link-name">{{item.name}}</div>
          <div class="link-db">{{item.db}}</div>
        </div>
        <div class="link-item-right">
          <el-tooltip content="编辑连接" placement="top">
            <i class="link-edit el-icon-edit-outline" @click="editLink($event, item)"></i>
          </el-tooltip>
          <el-tooltip content="删除连接" placement="top">
            <i class="link-delete el-icon-delete" @click="deleteLink($event, item)"></i>
          </el-tooltip>
        </div>
      </div>
    </div>
    <div v-show="!linkList.length">暂无连接</div>
    <div v-if="curLink.id">
      <div>选择素材<el-tooltip content="模型训练只能选择1个表" placement="top"><i class="el-icon-question"></i></el-tooltip></div>
      <div class="radio-box">
        <div>
          <el-radio-group v-model="type" size="small">
            <el-radio-button label="table">选择表</el-radio-button>
            <el-radio-button label="sql">SQL语句</el-radio-button>
          </el-radio-group>
        </div>
        <div><el-input v-model="keyword" size="small" clearable placeholder="搜索表名" @keyup.enter.native="handleKeyword"></el-input></div>
      </div>
      <div v-loading="tableLoading" v-show="type === 'table'">
        <div class="link-list">
          <div
            v-for="(item, index) in tableList"
            :key="index"
            class="link-item"
            :class="{ 'active': item === curTable}"
            @click="chooseTable(item)">
            <div class="link-item-left">{{item}}</div>
          </div>
        </div>
        <mine-pagination
          @numberChange="numberChange"
          :total="tableTotal"
          :page-size="tablePageSize"
          :current-page="tableCurrentPage">
        </mine-pagination>
      </div>
      <div v-show="type === 'sql'">
        <el-input type="textarea" :autosize="{ minRows: 4 }" v-model="sql"></el-input>
        <el-button type="primary" size="small" @click="runSql">执行</el-button>
      </div>
      <div>数据预览<el-tooltip content="数据预览展示前10条数据" placement="top"><i class="el-icon-question"></i></el-tooltip></div>
      <el-table
        class="table border-table"
        :data="tableData"
        style="width: 100%"
        v-loading="tableDataLoading"
        :max-height="300"
        ref="multipleTable">
        <el-table-column
          v-for="(item, index) in colArr"
          :key="index"
          :prop="item"
          :label="item">
          <template slot-scope="scope">{{scope.row[item]}}</template>
        </el-table-column>
      </el-table>
    </div>
    <mine-dialog :appendToBody="true" :dialogFormVisible="flag" :width="'700px'" :modalFlag="modalFlag" :title="title" :showClose="showClose" @close="close">
      <linkModal ref="linkModal" v-if="assembly === '新建连接'" slot="option" :flag="flag" @close="close" @submit="addLinkCallback"></linkModal>
      <linkModal ref="editLinkModal" v-if="assembly === '编辑连接'" slot="option" :flag="flag" @close="close" @submit="editLinkCallback" :info="info" isEdit></linkModal>
    </mine-dialog>
  </div>
</template>
<script>
import { modalMixins } from '../mixins';
import linkModal from './linkModal';
export default {
  mixins: [modalMixins],
  components: {
    linkModal,
  },
  data () {
    return {
      linkList: [],
      curLink: {},
      type: 'table',
      tableList: [],
      curTable: '',
      tablePageSize: 10,
      tableCurrentPage: 1,
      tableLoading: false,
      tableTotal: 0,
      sql: '',
      tableDataLoading: false,
      tableData: [],
      colArr: [],
      info: {},
      keyword: ''
    }
  },
  methods: {
    async getResult () {
      let result = null;
      let sql = '';
      if (!this.curLink.id) {
        this.$message({ type: 'warning', message: '请选择数据库' });
        return;
      }
      if (this.type === 'table') {
        if (!this.curTable) {
          this.$message({ type: 'warning', message: '请选择表' });
          return;
        }
        // const db = this.curLink.db;
        const tableName = this.curTable;
        sql = `select * from ${tableName};`;
      } else {
        if (!this.sql) {
          this.$message({ type: 'warning', message: '请输入sql' });
          return;
        }
        try {
          const res = await this.$store.dispatch('dataAdminDatabaseinfoCheckoutIllegal', {
            sql: this.sql,
            type: this.curLink.platform,
          });
          // select * from 3867iris;
          const resResult = res.data || {};
          if (resResult.success) {
            sql = this.sql;
          } else {
            this.$message({ type: 'error', message: resResult.msg || 'sql校验失败' });
          }
        } catch (e) {
          console.error(e);
        }
      }
      result = {
        id: this.curLink.id,
        sql,
      };
      return result;
    },
    init () {
       // 加载历史数据库连接
      this.getLinkList();
    },
    // link
    async getLinkList () {
      const params = {};
      try {
        const res = await this.$store.dispatch('dataAdminDatabaseinfoHistory', params);
        const result = res.data || {};
        if (result.success) {
          const data = result.data && result.data.length ? result.data : [];
          this.linkList = data;
        } else {
          this.linkList = [];
        }
        this.curLink = {};
      } catch (e) {
        console.error(e);
      }
    },
    addLink () {
      this.flag = true;
      this.showClose = true;
      this.title = '新建连接';
      this.assembly = '新建连接';
      this.$nextTick(() => {
        this.$refs.linkModal.show();
      });
    },
    addLinkCallback () {
      this.getLinkList();
    },
    //  选中当前数据库连接，加载所有表信息
    chooseLink (val) {
      this.curLink = val;
      this.getTableList(true);
    },
    editLink (event, val) {
      event.stopPropagation();
      this.info = { ...val };
      this.flag = true;
      this.showClose = true;
      this.title = '编辑连接';
      this.assembly = '编辑连接';
      this.$nextTick(() => {
        this.$refs.editLinkModal.show();
      });
    },
    editLinkCallback () {
      this.getLinkList();
    },
    deleteLink (event, val) {
      event.stopPropagation();
      this.$confirm('是否删除此连接?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const params = { id: val.id || '' };
        try {
          const res = await this.$store.dispatch('dataAdminDatabaseinfoDeleteDataBase', params);
          const result = res.data || {};
          if (result.success) {
            this.$message({ type: 'success', message: '删除成功!'});
            this.getLinkList();
          } else {
            this.$message({ type: 'error', message: '删除失败!'});
          }
        } catch (e) {
          this.$message({ type: 'error', message: '删除失败!'});
          console.error(e);
        }
      }).catch(() => {});
    },
    // table
    async getTableList (flag) {
      if (flag) {
        this.tableCurrentPage = 1;
      }
      const params = {
        id: this.curLink.id,
        pageSize: this.tablePageSize,
        page: this.tableCurrentPage,
        likeStr: this.keyword || '',
      };
      this.tableLoading = true;
      try {
        const res = await this.$store.dispatch('dataAdminDatabaseinfoGetTableListId', params);
        const result = res.data || {};
        if (result.success) {
          const data = result.data || {};
          this.tableList = data.list && data.list.length ? data.list : [];
          this.tableTotal = data.rowCount || 0;
        } else {
          this.tableList = [];
          this.tableTotal = 0;
        }
      } catch (e) {
        console.error(e);
      }
      this.tableLoading = false;
    },
    handleKeyword (event) {
      this.getTableList(true);
    },
    numberChange (val) {
      switch (val.flag) {
        case 'pageSize':
          this.tablePageSize = val.pageSize;
          this.getTableList(true);
          break;
        case 'currentPage':
          this.tableCurrentPage = val.currentPage;
          this.getTableList(false);
          break;
        default:
          break;
      }
    },
    chooseTable (val) {
      this.curTable = val;
      this.getByTable();
    },
    // 加载表信息及所有数据
    async getByTable () {
      const params = {
        id: this.curLink.id,
        tableName: this.curTable,
      };
      this.tableDataLoading = true;
      try {
        const res = await this.$store.dispatch('dataAdminDatabaseinfoGetByTable', params);
        const result = res.data || {};
        let data = [];
        if (result.success) {
          data = result.data && result.data.length ? result.data : [];
        }
        this.colArr = [];
        if (data.length) {
          const row = data[0];
          for (let i in row) {
            this.colArr.push(i);
          }
        }
        this.$nextTick(() => {
          this.tableData = [...data];
        });
      } catch (e) {
        console.error(e);
      }
      this.tableDataLoading = false;
    },
    // sql
    async runSql () {
      if (!this.sql) {
        this.$message({ type: 'warning', message: '请输入sql' });
        return;
      }
      this.getBySql();
    },
    async getBySql () {
      const params = {
        id: this.curLink.id,
        sql: this.sql,
      };
      this.tableDataLoading = true;
      try {
        const res = await this.$store.dispatch('dataAdminDatabaseinfoGetBySql', params);
        const result = res.data || {};
        let data = [];
        if (result.success) {
          data = result.data && result.data.length ? result.data : [];
        }
        this.colArr = [];
        if (data.length) {
          const row = data[0];
          for (let i in row) {
            this.colArr.push(i);
          }
        }
        this.$nextTick(() => {
          this.tableData = [...data];
        });
      } catch (e) {
        console.error(e);
      }
      this.tableDataLoading = false;
    }
  },
  created () {
    this.init();
  }
}
</script>
<style lang="less" scoped>
@import '~@/style/variables.less';
.new-link-btn {
  margin-left: 10px;
  .new-link-icon {
    font-size: 14px;
    margin-right: 5px;
  }
}
.link-list {
  width: 100%;
  // width: 600px;
  max-height: 300px;
  overflow-y: auto;
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
}
.link-item {
  width: 48%;
  // width: 280px;
  height: 70px;
  padding: 0 20px;
  box-sizing: border-box;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 10px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #f5f7f9;
  border: 1px solid #f5f7f9;
  line-height: 28px;
  &:hover {
    background-color: #eff1f2;
  }
  &.active {
    color: @--color-primary;
    border: 1px solid @--color-primary;
  }
}
.link-item-left {
  width: 180px;
}
.link-edit {
  margin-right: 5px;
}
.radio-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}
</style>
